#!/bin/bash

sep="
###########################
"
# videoblerg.wordpress.com/2017/11/10/ffmpeg-and-how-to-use-it-wrong/comment-page-1/
file="$1"
vcodec=x264
pix_fmt=yuv420p
vbitrate=500
#################################
preset=veryslow
# presets: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow
tune=film
# tunes: film,animation, grain, stillimage, psnr, ssim, fastdecode, zerolatency

bufsize=$((vbitrate))
maxrate=$((vbitrate + vbitrate/3))

ffmpeg_cmd="ffmpeg -nostdin -hide_banner -analyzeduration 2147483647 -probesize 2147483647"
endopts="-max_muxing_queue_size 9999"

outfile="${file%.*}.$vcodec.$pix_fmt.v$vbitrate.$preset.$tune.mp4"
fix="${file%.*}.fix.mkv"

cleanup() {
    rm ffmpeg2pass-0.log*
    rm "$fix"
}

trap cleanup EXIT

cmd=( $ffmpeg_cmd -i "$file" -r 10 -c:v ffvhuff -an $endopts "$fix" )
echo "$sep${cmd[@]}$sep"
"${cmd[@]}"

cmd=( $ffmpeg_cmd -i "$fix" -r 10 -pix_fmt "$pix_fmt" -vsync 1 -vcodec lib$vcodec -b:v: ${vbitrate}k -bufsize ${bufsize}k -maxrate ${maxrate}k -preset $preset -profile:v high -tune $tune -pass 1 -an $endopts -f mp4 -y /dev/null )
echo "$sep${cmd[@]}$sep"
"${cmd[@]}"

cmd=( $ffmpeg_cmd -i "$fix" -r 10 -pix_fmt "$pix_fmt" -vsync 1 -vcodec lib$vcodec -b:v: ${vbitrate}k -bufsize ${bufsize}k -maxrate ${maxrate}k -preset $preset -profile:v high -tune $tune -pass 2 -an $endopts -f mp4 "$outfile" )
echo "$sep${cmd[@]}$sep"
"${cmd[@]}"
